from django.db import models

# Create your models here.
from airconfig.config import config
from django.urls import path, include
from django.http import HttpResponse, JsonResponse
from scheduler.schedule import Request
import json
from adm.views import room_list
from adm.models import master
from scheduler.schedule import sche
from common.models import Detail, Customer
from .views import customer
from datetime import datetime
from django.core import signing




# 控制器
class Customer_Controller():
    def get_request(self):
        urlpatterns=[
            path('poweroff/', self.poweroff),
            path('poweron/', self.poweron),
            path('changetargettemp/', self.changetargettemp),
            path('changefanspeed/', self.changefanspeed),
            path('requeststate/', self.requeststate),
            path('signup/', customer.signup),
        ]

    def checktoken(self,request):
        # 用户的token是rid|*****,checkinDate|******
        # 分隔符...
        token = request.META.get("HTTP_AUTHORIZATION")
        splitlist=token.split(',')
        strlist1 = splitlist[0].split('|')
        src1 = signing.loads(strlist1[1])
        strlist1[0] = strlist1[0].encode("latin1").decode("utf-8")
        strlist2 = splitlist[1].split('|')
        src2 = signing.loads(strlist2[1])
        strlist2[0] = strlist2[0].encode("latin1").decode("utf-8")
        print("receiving token from",src1['rid'])
        if strlist1[0] == src1['rid'] and strlist2[0] == src2['checkinDate']:
            return 0
        else:
            return 1



    def changetargettemp(self, request):
        request.params = json.loads(request.body)
        roomid = request.params['roomid']
        targetTemp = request.params['targetTemp']
        print("receiving request:change target temp,target room:roomid")
        return_value = dict()
        if targetTemp > config.hot_sup or targetTemp < config.cold_sub or (roomid not in config.room_list) or self.checktoken(request):
            return_value['error_code'] = 1
        else:
            request_tmp = sche.get_request(roomid)
            duration = sche.get_time(roomid)  # 这应该是实时获取servicetime的函数
            record = Detail.objects.create(rid=roomid, lastinTime=request_tmp.serviceStartTime,
                                           requestDuration=duration, fanSpeed=request_tmp.fanSpeed,
                                           fee=request_tmp.feeRate * duration, cmd=" change_tmp")
            # 虽然记录了详单，但是request详单参数不会进行改变
            request_tmp.targetTemp = targetTemp
            queue_now = sche.get_request_pos(roomid)
            if queue_now == "service":
                if (request_tmp.wordmode == 1 and request_tmp.targetTemp > request_tmp.currentTemp) or (
                        request_tmp.wordmode == -1 and request_tmp.targetTemp < request_tmp.currentTemp):  # 此处需要换成实时温度
                    sche.one_room_pause(roomid)
            return_value['error_code'] = 0
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

    def poweron(self, request):
        # 实例化一个新的request,并交给调度
        request.params = json.loads(request.body)
        roomid = request.params['roomId']
        targetTemp = request.params['targetTemp']
        fanspeed = request.params['fanSpeed']
        print("receiving request:poweron,targetroom:",roomid)
        return_value = dict()
        queue_now = sche.get_request_pos(roomid)  # 如果为None，说明不在任意一个队列，说明没有正在工作
        if targetTemp > config.hot_sup or targetTemp < config.cold_sub or (
                roomid not in config.room_list) or queue_now != None or self.checktoken(request):
            print("if")
            return_value['error_code'] = 1
        # 如果接通电源，master的属性有变化，此处需要判断
        else:
            print("else")
            for room in room_list:
                print(room.roomid)
                if room.roomid == roomid:
                    print(room.roomid)
                    currenttemp = room.get_current_temp()
                    print(currenttemp)
                    room.onoff=1
                    room.freeRate=config.fee_rates
                    request_on = Request(roomid, currenttemp, targetTemp, fanspeed, config.fee_rates,config.temp_rate,config.default_work_mode)
                    record = Detail.objects.create(rid=roomid, lastinTime=request_on.serviceStartTime,
                                                   requestDuration=0, fanSpeed=request_on.fanSpeed,
                                                   fee=0, cmd=" power_on")
                            # 调用schedule
                    sche.one_room_power_on(request_on)
                    return_value['error_code'] = 0
                    break
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

    def poweroff(self, request):
        # 生成详单，并且删除request
        request.params = json.loads(request.body)
        roomid = request.params['roomid']
        print("receiving request:poweroff,targetroom:",roomid)
        return_value = dict()
        queue_now = sche.get_request_pos(roomid)  # 如果不为None，说明正在工作
        if (roomid not in config.room_list) or queue_now == None or self.checktoken(request):
            return_value['error_code'] = 1
        else:
            request_off = sche.get_request(roomid)
            duration = request_off.serviceTime  # 这应该是实时获取servicetime的函数
            record = Detail.objects.create(rid=roomid, lastinTime=request_off.serviceStartTime,
                                           requestDuration=duration, fanSpeed=request_off.fanSpeed,
                                           fee=request_off.feeRate * duration, cmd="power_off")
            # 将当前温度传入到其对应的房间对象中
            for room in room_list:
                if room.roomid == roomid:
                    room.currenttemp = request_off.currentTemp  # 需要温度获取函数
                    room.lastoff = datetime.now()
                    room.onoff=0
            sche.one_room_power_off(roomid)
            return_value['error_code'] = 0
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

    def changefanspeed(self, request):
        request.params = json.loads(request.body)
        roomid = request.params['roomid']
        targetFan = request.params['fanSpeed']
        print("receiving request:poweroff,targetroom:",roomid)
        return_value = dict()
        queue_now = sche.get_request_pos(roomid)  # 如果不为None，说明正在工作
        print(roomid not in config.room_list)
        print("是否在队列中",queue_now == None)
        print(self.checktoken(request))
        #m没有判断风速范围
        # print(targetFan < config.fan_sub or targetFan > config.fan_sup)
        #没有判断是否在工作队列、等待队列、回温队列
        if (roomid not in config.room_list) or self.checktoken(request):
            return_value['error_code'] = 1
        else:
            request_fan = sche.get_request(roomid)
            duration = sche.get_time(roomid)  # 这应该是实时获取servicetime的函数
            record = Detail.objects.create(rid=roomid, lastinTime=request_fan.serviceStartTime,
                                           requestDuration=duration, fanSpeed=request_fan.fanSpeed,
                                           fee=request_fan.feeRate * duration, cmd="change_fan")
            # 修改request详单相关参数,此处需要后续确认
            request.fee = 0

            # request_fan.fanSpeed = targetFan
            # if request_fan.fanSpeed == 0:
            #     feeRate = config.feeRate_L
            # elif request_fan.fanSpeed == 1:
            #     feeRate = master.feeRate_M
            # else:
            #     feeRate = master.feeRate_H
            # request_fan.feeRate = feeRate
            sche.change_fan_speed(roomid)
            return_value['error_code'] = 0
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

    def requeststate(self, request):
        request.params = json.loads(request.body)
        roomid = request.params['roomid']
        print("receiving request:request state,target room:roomid")
        return_value = dict()
        # queue_now = sche.get_request_pos(roomid)  # 如果不为None，说明正在工作
        # if (roomid not in config.room_list) or queue_now == None or self.checktoken(request):
        #     return_value['error_code'] = 1
        # else:
        checkindate_list = Customer.objects.filter(rid=roomid).values_list('checkinDate', flat=True)
        checkindate = max(checkindate_list)
        # 从checkinadte到现在所有的detail的fee之和
        detail_list = Detail.objects.filter(rid=roomid, createtime__gt=checkindate).values_list('fee',"cmd")
        sum = 0
        for fee in detail_list:
            if fee[1] in ["power_off","schedule_kick","target_temp","change_fan"]:
                sum += fee[0]
        for room in room_list:
            if room.roomid == roomid:
                room.totalCost=sum
        request_check = sche.get_request(roomid)
        duration = request_check.serviceTime  # 这应该是实时获取servicetime的函数
        sum += duration * request_check.feeRate
        return_value['error_code'] = 0
        return_value["data"] = {}
        return_value["data"]['currentTemp'] = request_check.currentTemp
        return_value["data"]['totalFee'] = sum
        return_value["data"]['currentFee'] = request_check.feeRate
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

customer_controller=Customer_Controller()


urlpatterns = [
    path('poweroff/', customer_controller.poweroff),
    path('poweron/', customer_controller.poweron),
    path('changetargettemp/', customer_controller.changetargettemp),
    path('changefanspeed/', customer_controller.changefanspeed),
    path('requeststate/',customer_controller.requeststate),
    path('signup/', customer.signup),
]

